package com.bw.dg.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {

	public static Map<String,String> fileUpload(MultipartFile multipartFile) {
		if (multipartFile == null)
			return null;
		Map<String,String> map = new HashMap<>();
		String fileName=multipartFile.getOriginalFilename();// 文件原名称
		String path=uploadPath()+fileName;// 文件路径
		System.out.println("上传的文件原名称:"+fileName);
		// 自定义的文件名称
		System.out.println("存放文件的路径:"+path);
		// 转存文件到指定的路径
		try {
			multipartFile.transferTo(new File(path));
			map.put("fileName",fileName);
			return map;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String uploadPath(){
		return System.getProperty("user.dir")+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+ "static" +File.separator;// 文件路径
	}

	public static void fileDownLoad(String filename, HttpServletRequest request,
                                    HttpServletResponse response)  {

		// 设置文件的MiMe类型
		response.setContentType(request.getServletContext().getMimeType(
				filename));
		// 设置content-dispsition
		response.setHeader("Content-Disposition", "attachment;filename="
				+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+".xls");
		// 读取目标文件，通过response将目标文件写到客户端
		try {
			// 读取文件
			InputStream in = new FileInputStream(filename);
			OutputStream out = response.getOutputStream();
			// 写文件
			int b = 0;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
}
